<?php
class Categories extends MY_Controller{

	function __construct()
	{
		parent::__construct();
		if(!$this->aauth->is_loggedin()){
			redirect('login');
		}
	}

	function index()
	{
		redirect('categories/viewCategory/1');
	}

	function error_404()
	{
		$data['title'] = $this->title('产品分类');
		$this->load->view($this->theme.'/header',$data);
		$this->load->view($this->theme.'/category/error_404');
		$this->load->view($this->theme.'/footer');
	}


	function viewCategory($parent_id = null)
	{
		if(!is_numeric($parent_id)){
			redirect('categories');
		}else{

			$cat = category::find('all',array('conditions'=>array('parent_id = '. $parent_id),'order'=>'position asc'));
			if(!$cat){
				redirect('categories/error_404');
			}else{
				$data['title'] = $this->title('产品分类');
				$data['category'] = $cat;
				$data['parent'] = category::find_by_id($parent_id);
				$this->load->view($this->theme.'/header',$data);
				$this->load->view($this->theme.'/category/index');
				$this->load->view($this->theme.'/footer');
			}

		}
	}

	function addCategory()
	{
		if($_POST){
			$this->form_validation->set_rules('name_cn','中文名称','required');
			$this->form_validation->set_rules('name_en','荷兰语名称','required');
			$this->form_validation->set_rules('name_nl','英文名称','required');
			$this->form_validation->set_rules('cat_id','分类','required');

			$this->form_validation->set_error_delimiters('<span class="text-red">', '</span>');
			if($this->form_validation->run() == false){

			}else{
				$parent_id = $_POST['cat_id'];
				$level_depth = category::find_by_id($parent_id)->level_depth+1;
				$name_cn = $_POST['name_cn'];
				$name_en = $_POST['name_en'];
				$name_nl = $_POST['name_nl'];
				$active = 1;
				$positionItem = category::find('all',array('conditions'=>array('parent_id'=>$parent_id)));
				$positionCount = count($positionItem);
				$position = $positionCount+1;
				$text_en = $_POST['text_en'];
				$text_nl = $_POST['text_nl'];
				$friendly_url_en = str_replace(" ","-", $_POST['name_en']);
				$friendly_url_nl = str_replace(" ","-", $_POST['name_nl']);
				$newCatData = array(
				'parent_id'=>$parent_id,
				'level_depth'=>$level_depth,
				'name_en'=>$name_en,
				'name_cn'=>$name_cn,
				'name_nl'=>$name_nl,
				'position'=>$position,
				'text_en'=>$text_en,
				'text_nl'=>$text_nl,
				'friendly_url_en'=>$friendly_url_en,
				'friendly_url_nl'=>$friendly_url_nl
				);
				$newCat = new category($newCatData);
				$newCat->save();
				if($newCat){
					redirect('categories');

				}else{
					$data['msg'] = array(array('code'=>3,'msg'=>'创建新的分类时遇到错误.'));
				}
			}

		}
		$data['title'] = $this->title('产品分类 > 添加分类');
		$data['category'] = $this->categorylist->level();
		$this->load->view($this->theme.'/header',$data);
		$this->load->view($this->theme.'/category/addCategory');
		$this->load->view($this->theme.'/footer');
	}

	function editCategory($cat_id = null)
	{
		if(!is_numeric($cat_id)){
			redirect('categories');
		}else{
			$cat = category::find_by_id($cat_id);
			if(!$cat){
				redirect('categories/error_404');
			}else{
				if($_POST){
					$this->form_validation->set_rules('name_cn','中文名称','required');
					$this->form_validation->set_rules('name_en','荷兰语名称','required');
					$this->form_validation->set_rules('name_nl','英文名称','required');
					$this->form_validation->set_rules('cat_id','分类','required');

					$this->form_validation->set_error_delimiters('<span class="text-red">', '</span>');
					if($this->form_validation->run() == false){

					}else{

						$msg = array();
						$name_cn = $_POST['name_cn'];
						$name_en = $_POST['name_en'];
						$name_nl = $_POST['name_nl'];
						$text_en = $_POST['text_en'];
						$text_nl = $_POST['text_nl'];
						$new_parent_id = $_POST['cat_id'];
						if($new_parent_id != $cat->parent_id ){
							$new = $this->changeParent($cat_id,$cat->parent_id, $new_parent_id);
							if($new){
								$msg[] = array(array('code'=>1,'msg'=>'分类修改成功'));
							}else{
								$msg[] = array(array('code'=>3,'msg'=>'分类修改不成功'));
							}

						}
						$cat->name_cn = $name_cn;
						$cat->name_en = $name_en;
						$cat->name_nl = $name_nl;
						$cat->text_en = $text_en;
						$cat->text_nl = $text_nl;
						if($cat->save()){
							$msg[] = array(array('code'=>1,'msg'=>'信息修改成功'));
						}else{
							$msg[] = array(array('code'=>3,'msg'=>'信息修改不成功'));
						}
						$data['msg'] = $msg;

					}
				}
				$data['title'] = $this->title('产品分类 > 编辑分类');
				$data['firstLevel'] = category::find_by_level_depth(0);
				$data['category'] = $this->categorylist->level($cat->id,$cat->parent_id);
				$data['cat'] = category::find_by_id($cat_id);
				$this->load->view($this->theme.'/header',$data);
				$this->load->view($this->theme.'/category/editCategory');
				$this->load->view($this->theme.'/footer');
			}
		}

	}


	function changeStatus()
	{
		if(!$_POST){
			redirect('categories/error_404');
		}else{
			if($_POST['action'] == 0 ){
				$action = 1;
			}else{
				$action = 0;
			}
			$status = category::find_by_id($_POST['id']);
			$status->active = $action;
			if($status->save()){
				echo json_encode(array('result'=>true));
			}else{
				echo json_encode(array('result'=>false));
			}
		}
	}


	function changePosition()
	{
		if(!$_POST){
			redirect('categories/error_404');
		}else{
			$cat = category::find_by_id($_POST['id']);
			$neighbor = category::find_by_position_and_parent_id($cat->position+$_POST['action'],$cat->parent_id);
				
			$cat->position = $cat->position+$_POST['action'];
			$cat->save();
			$neighbor->position = $neighbor->position-$_POST['action'];
			$neighbor->save();
				
			echo json_encode(array('result'=>true));
				
		}
	}

	function deleteCatThumb()
	{
		if(!$_POST){
			redirect('categories/error_404');
		}else{
			$cat = category::find_by_id($_POST['id']);
			
				if($cat->thumb){
					$file_to_delete = $cat->thumb;
					$path_file = '../uploads/catThumbs/'.$file_to_delete;
					unlink($path_file);
				}
				$cat->thumb = null;
				$cat->save();
			echo json_encode(array('result'=>true));
				
		}
	}
	
	function addThumb()
	{
		if($_POST)
		{
			$md5Date = Date("Y_m_d_H_i_s");
			$config['upload_path'] = '../uploads/catThumbs';
			$config['allowed_types'] = 'jpg|png';
			$config['max_size'] = '2000';
			$config['file_name'] = 'thumb_'.$md5Date;
			$this->load->library('upload', $config);

			if(!$this->upload->do_upload()){
				$error = array('validate'=>FALSE,'error' => $this->upload->display_errors());
				var_dump($error);
			}else{
				$upload_data = $this->upload->data();
				$thumbName = $upload_data['file_name'];
				$img_width = $upload_data['image_width'];
				$img_height = $upload_data['image_height'];
				$this->load->library('image_lib');
					
				$config['image_library'] = 'gd2';
				$config['source_image'] = '../uploads/catThumbs/'.$thumbName;
				$config['new_image'] = '../uploads/catThumbs/'.$thumbName;
				$config['create_thumb'] = FALSE;
				$config['maintain_ratio'] = FALSE;
				if($img_width > $img_height){

					$config['width'] = '200';
					$config['height'] = round($img_height *(200/$img_width));
				}elseif($img_width == $img_height){
					$config['height'] = $config['width'] = '200';
				}else{
					$config['height'] = '200';
					$config['width'] = round($img_width *(200/$img_height));
				}
				$this->image_lib->initialize($config);
				$this->image_lib->resize();

				$category = category::find_by_id($_POST['category_id']);
				if($category->thumb){
					$file_to_delete = $category->thumb;
					$path_file = '../uploads/catThumbs/'.$file_to_delete;
					unlink($path_file);
				}
				$category->thumb = $thumbName;
				$category->save();
				redirect('categories/editCategory/'.$category->id);
			}
		}else{
			redirect('categories/error_404');
		}
	}



	private function changeParent($child_id,$current_parent_id, $new_parent_id)
	{
		$child = category::find_by_id($child_id);
		/* new change */
		$new_parent = category::find_by_id($new_parent_id);
		$new_neighbor = category::find('all',array('conditions'=>array('parent_id'=>$new_parent_id)));
		$positionCount = count($new_neighbor);
		$position = $positionCount+1;
		$level_depth = $new_parent->level_depth+1;
		$child->parent_id = $new_parent_id;
		$child->level_depth = $level_depth;
		$child->position = $position;
		$child->save();

		/* re-order current cat list  */
		$newOrder = category::find('all',array('conditions'=>array('parent_id =? AND position > ?',$current_parent_id, $child->position)));
		foreach ($newOrder as $n){
			$nn = category::find_by_id($n->id);
			$nn->position = $n->position-1;
			$nn->save();
		}

		return true;

	}


}